<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 2020-06-17
 * Time: 16:22
 * 创建项目孵化评价订单
 */

namespace app\api\service\project;


use app\api\model\ProjectHatchCommentOrder;
use app\api\model\System;
use app\api\service\Token;
use app\lib\exception\ParameterException;
use think\Db;
use think\Exception;

class CommentOrderSer extends Token
{
    /**
     * 1.判断会员权限
     * 2.判断是否有评论的权限
     * 3.有进行提示
     * 4.没有添加订单  返回支付number
     */

    // 用户id
    private $uid;

    // 项目孵化ID
    private $projectHatchId;

    function __construct($project_id)
    {
        $this->projectHatchId = $project_id;
        $this->uid = self::getCurrentUid();
        self::judgeMember();
    }

    // 入口方法
    public function entrance()
    {
        return $this->judgeProjectComment();
    }

    // 判断评论权限
    private function judgeProjectComment()
    {
        $info = self::judgeProjectHatch();
        if($info) {
            throw new ParameterException([
                'errorCode' => 20001,
                'msg' => [
                    'hatch' => '您有项目评论的权限'
                ]
            ]);
        }
        return $this->createOrder();
    }

    // 创建订单信息
    private function createOrder()
    {
        // 删除未支付的订单
        ProjectHatchCommentOrder::destroy(['user_id' => $this->uid]);
        $system = System::get(1);
        // 创建订单
        Db::startTrans();
        try{
            $mode = ProjectHatchCommentOrder::create([
                'user_id' => $this->uid,
                'price' => $system['project_hatch_comment_price'],
                'order_no' => self::makeOrderNo(),
                'project_hatch_id' => $this->projectHatchId
            ]);
            $out_trade_no = '4you2020'.$mode->id;
            $mode->out_trade_no = $out_trade_no;
            $mode->save();
            Db::commit();
            return writeJson(201, [ 'out_trade_no'=>$out_trade_no ], '订单生成成功！');
        }
        catch (Exception $ex) {
            Db::rollback();
            throw $ex;
        }
    }
}